var editNum = 0;

/**
 * 修改
 */
function editReource(){
	if(editNum==0){
		editNum+=1;
		$.post(rootPath+"/resource/updateResource",$('#editResourceForm').serialize(),function(data){
			if(data == "ok"){
				$(".tsContext").html("修改成功!");
				$('.res_divk').toggle();
				$('#zy_box').toggle();
				setTimeout("getList()",1000);
			}else{
				$(".tsContext").html(data);
				$('#zy_box').toggle();
				$('.res_divk').toggle();
				editNum=0;
			}
		});
	}
}

/**
 * @param systemId
 */
function addSystem(){
	$("#parentName").html("请选择");
	var systemId = $("#systemId").val();
	var nodes = []; 
	$.ajax({
		url : rootPath + "/resource/getResourceBySystem",
		async : false,
		dataType : 'json',
		data:{systemId:systemId},
		type : 'post',
		success : function(data) {
			if (data != null) {
				$.each(data, function(index, row) {
					nodes.push({
						id : row.id,
						parentId : row.parentId,
						name : row.resourceName
					});
				});
			}
		},
		fail : function() {
			alert("fail!!!!!!!");
		}
	});

	/**
	 * zTree设置
	 */
	var setting = {
		data : {
			simpleData : {
				enable : true,
				idKey : 'id',
				pIdKey : 'parentId',
				rootPId : "0"
			}
		},
		callback : {
			onClick : onClick
		}
	};
	var treeObj = $.fn.zTree.init($("#zTree"), setting, nodes);
	treeObj.expandAll(true);
}

function onClick(e, treeId, treeNode) {
	// 判断div是否影藏状态
	var isHidden = $("#orgInfo").is(":hidden");
	if (isHidden) {
		$("#orgInfo").show();
	}
	var zTree = $.fn.zTree.getZTreeObj("zTree"), nodes = zTree
			.getSelectedNodes(), name = "", id = "", parentId = "";
	nodes.sort(function compare(a, b) {
		return a.id - b.id;
	});
	for (var i = 0, l = nodes.length; i < l; i++) {
		name += nodes[i].name + ",";
		id += nodes[i].id + ",";
		parentId += nodes[i].parentId + ",";
	}
	if (id.length > 0)
		id = id.substring(0, id.length - 1);
	if (name.length > 0)
		name = name.substring(0, name.length - 1);
	if (parentId.length > 0)
		parentId = parentId.substring(0, parentId.length - 1);

	$("#parentName").html(name);
	$("#parentId").val(id);
}

/**
 * 判断是否为空
 * @param obj
 * @returns {Boolean}
 */
function isNull(obj){
	if(obj != null && obj != "" && obj != undefined){
		return false;
	}
	return true;
}


function getList(){
	location.href = rootPath +"/page/resource/resource_list.jsp";
}

$(function(){
	addSystem();
	if(!isNull($("#parentId").val())){
		$("#parentName").html($("#parentNameOld").val());
	}
	$("#edit_resource_edit").click(function(){
		editReource();
	});
	$("#systemId").next().children("h4").html($("#systemId").find("option:selected").text());
	$("#systemId").change(function(){
		addSystem();
	});
	$("#getList").click(function(){
		getList();
	});
	
	$("#ztreedl").click(function(){
		var className= $(this).attr("class");
		if(className == "hover"){
			$(this).attr("class","");
		}else{
			$(this).attr("class","hover");
		}
		
	});
	$("#zTree").mouseleave(function(){
		$("#ztreedl").attr("class","");
	});
});